package com.ruoze.bdp.dao;

import com.ruoze.bdp.entity.DataSourceEntity;
import com.ruoze.bdp.entity.datasource.DataSourceClusterVo;
import com.ruoze.bdp.entity.datasource.DataSourceRequest;
import com.ruoze.bdp.enums.DbType;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface IDataSourceRepository extends Repository<DataSourceEntity,Long>,
        JpaRepository<DataSourceEntity,Long>, JpaSpecificationExecutor<DataSourceEntity> {

    @Query(value = "SELECT new com.ruoze.bdp.entity.datasource.DataSourceClusterVo(ds, c) " +
            "FROM DataSourceEntity ds, ClusterEntity c " +
            "WHERE ds.clusterId = c.id and ds.status = '0' " +
            "and ( ds.clusterId=:#{#request.clusterId} or :#{#request.clusterId} is null )  " +
            "and ( ds.type=:#{#request.dateType} or :#{#request.dateType} is null or :#{#request.dateType} = '') " +
            "and ( ds.name like CONCAT('%', :#{#request.name}, '%')  or :#{#request.name} is null or :#{#request.name} = ''  )  ")
    Page<DataSourceClusterVo> findDataSourceClusterVoPage(@Param("request") DataSourceRequest request, Pageable pageable);


    @Query("select name from #{#entityName} d where d.type = :type")
    List<String> findNamesByType(@Param("type") DbType type);

    @Modifying
    @Transactional
    @Query("update #{#entityName} d set d.status = 1 where d.id = ?1")
    void logicalDeleteById(Long Id);

    @Modifying
    @Transactional
    @Query("update #{#entityName} d set d.status = 1 where d.id in (?1)")
    void logicalDeleteBatch(List<Long> ids);

}
